#include "choosefrienddialog.h"

#include <QScrollArea>
#include <QScrollBar>
#include <QPainter>
#include "model/datacenter.h"
#include "toast.h"

using namespace model;
#include "debug.h"

/////////////////////////////////////////////////////////////////
/// 选择好友窗口中的一个 元素/好友项
/////////////////////////////////////////////////////////////////
ChooseFriendItem::ChooseFriendItem(ChooseFriendDialog* owner, const QString& userId, const QIcon &avatar,
                                   const QString &name, bool checked)
    : userId(userId)
{
    // 1. 设置控件的基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 2. 设置布局管理器
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(20, 0, 20, 0);
    this->setLayout(layout);

    // 3. 创建复选框
    checkBox = new QCheckBox();
    checkBox->setChecked(checked);
    checkBox->setFixedSize(20, 20);
    QString style = "QCheckBox { background-color: transparent; }"
                    "QCheckBox::indicator { width: 20px; height: 20px; "
                    "image: url(:/resource/image/unchecked.png); }";
    style += "QCheckBox::indicator:checked { image: url(:/resource/image/checked.png); }";
    checkBox->setStyleSheet(style);

    // 4. 创建头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40, 40);
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setIcon(avatar);

    // 5. 创建名字
    nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel { background-color: transparent; }");

    // 6. 添加到布局管理器
    //layout->addWidget(searchEdit);
    layout->addWidget(checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);

    // 7. 连接信号槽
    connect(checkBox, &QCheckBox::toggled, this, [=](bool checked) {
        if (checked)
        {
            // 勾选则添加
            owner->addSelectedFriend(userId, avatar, name);
        }
        else
        {
            // 取消勾选
            owner->deleteSelectedFriend(userId);
        }
    });

}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    (void)event;
    QPainter painter(this);
    if (isHover)
    {
        painter.fillRect(this->rect(), QColor(232, 231, 231));
    }
    else
    {
        painter.fillRect(this->rect(), QColor(255, 255, 255));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent *event)
{
    (void)event;
    isHover = true;
    this->update();
}

void ChooseFriendItem::leaveEvent(QEvent *event)
{
    (void)event;
    isHover = false;
    this->update();
}


/////////////////////////////////////////////////////////////////
/// 选择好友的窗口
/////////////////////////////////////////////////////////////////



ChooseFriendDialog::ChooseFriendDialog(QWidget* parent, const QString& userId)
    : QDialog(parent)
    , userId(userId)
{
    // 1. 基本属性
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setFixedSize(600, 450);
    this->setStyleSheet("QDialog { background-color: rgb(255, 255, 255); }");
    this->setAttribute(Qt::WA_DeleteOnClose);

    // 2. 创建布局管理器
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    this->setLayout(layout);

    // 3. 针对左侧窗口进行初始化
    initLeft(layout);

    // 4. 右侧窗口初始化
    initRight(layout);

    // 5. 加载数据到窗口中
    initData();

}

void ChooseFriendDialog::initLeft(QHBoxLayout *layout)
{
    QVBoxLayout* vLayout = new QVBoxLayout();
    vLayout->setContentsMargins(0, 0, 0, 0);
    vLayout->setSpacing(0);
    layout->addLayout(vLayout);

    QWidget* searchWidget = new QWidget();
    searchWidget->setFixedHeight(60);

    vLayout->addWidget(searchWidget);

    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setContentsMargins(5, 0, 0, 0);
    searchWidget->setLayout(hlayout);

    // 搜索框
    QAction* search = new QAction();
    search->setIcon(QIcon(":/resource/image/search.png"));
    searchEdit = new QLineEdit();
    searchEdit->setFixedSize(230, 27);
    searchEdit->setPlaceholderText("搜索");
    searchEdit->setStyleSheet("QLineEdit { border-radius: 4px; background-color: rgb(232, 232, 232); }"
                            "QLineEdit:focus { background-color: rgb(250, 250, 250);"
                            "border: 1px solid rgb(241, 241, 241); }");
    searchEdit->addAction(search, QLineEdit::LeadingPosition);

    QWidget* spacer1 = new QWidget();
    spacer1->setFixedWidth(5);

    //hlayout->addWidget(spacer1);
    hlayout->addWidget(searchEdit);

    // 1. 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setFixedWidth(280);
    scrollArea->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; "
                                                   "background-color: rgb(255, 255, 255); }");

    scrollArea->setStyleSheet("QScrollArea { border: none; }");
    vLayout->addWidget(scrollArea);

    // 2. 创建 QWidget 设置到滚动区域中
    totalContainer = new QWidget();
    totalContainer->setFixedWidth(280);
    totalContainer->setObjectName("totalContainer");
    totalContainer->setStyleSheet("#totalContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(totalContainer);

    // 3. 创建左侧子窗口内部的 垂直布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    totalContainer->setLayout(vlayout);

#if TEST_UI
    QIcon defaultAvatar(":/resource/image/Mitsy.jpg");
    for (int i = 0; i < 25; ++i)
    {
        this->addFriend(QString::number(1000 + i), defaultAvatar, "野原美伢" + QString::number(i), false);
    }
#endif


}

void ChooseFriendDialog::initRight(QHBoxLayout *layout)
{

    QFrame *line = new QFrame();
    line->setFrameShape(QFrame::VLine);
    line->setFrameShadow(QFrame::Sunken);

    layout->addWidget(line);

    // 1. 创建右侧的布局管理器
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setContentsMargins(20, 0, 20, 22);
    gridLayout->setSpacing(10);
    layout->addLayout(gridLayout, 1);

    // 2. "提示" label
    QLabel* tipLabel = new QLabel();
    tipLabel->setText("选择联系人");
    tipLabel->setFixedWidth(100);
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    tipLabel->setStyleSheet("QLabel { margin-left: 5px; margin-top: 13px; "
                            "font-size: 14px; font-weight: 400; }");

    // 2.5 已选择 n 个联系人
    selectedLabel = new QLabel();
    // QString text = "已选择" + QString::number(ChooseFriendDialog::count) + "个联系人";
    // selectedLabel->setText(text);
    selectedLabel->setFixedHeight(30);
    selectedLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    selectedLabel->setStyleSheet("QLabel { margin-left: 67px; margin-top: 17px; "
                            "font-size: 11px; font-weight: 500; color: rgb(127, 127, 127);}");
    // selectedLabel->hide();

    // 3. 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px;"
                                                   "background-color: rgb(255, 255, 255); }");
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    scrollArea->setStyleSheet("QScrollArea { border: none; }");
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 4. 创建滚动区域中的 QWidget
    selectedContainer = new QWidget();
    selectedContainer->setObjectName("selectedContainer");
    selectedContainer->setStyleSheet("#selectedContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(selectedContainer);

    // 5. 创建 selectedContainer 中的 "垂直布局"
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    selectedContainer->setLayout(vlayout);

    // 6. 创建底部按钮
    QString okStyle = "QPushButton { color: rgb(158, 158, 158); background-color: rgb(235, 235, 235);"
                    "border: none; border-radius: 5px; }";
    // okStyle += "QPushButton:hover { background-color: rgb(56, 205, 127); }"
    //          "QPushButton:pressed { background-color: rgb(6, 173, 86); }";
    okBtn = new QPushButton();
    okBtn->setFixedSize(109, 30);
    okBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    okBtn->setText("完成");
    okBtn->setStyleSheet(okStyle);
    okBtn->setEnabled(false);


    QString cancelStyle = "QPushButton { color: rgb(7, 193, 96); background-color: rgb(243, 243, 243);"
                      "border: none; border-radius: 3px; }";
    cancelStyle += "QPushButton:hover { background-color: rgb(219, 219, 219); }"
               "QPushButton:pressed { background-color: rgb(206, 206, 206); }";

    QPushButton* cancelBtn = new QPushButton();
    cancelBtn->setFixedSize(109, 30);
    cancelBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    cancelBtn->setText("取消");
    cancelBtn->setStyleSheet(cancelStyle);

    QWidget* spacer = new QWidget();
    spacer->setFixedWidth(200);

    // 7. 添加到布局管理器中
    gridLayout->addWidget(tipLabel, 0, 0, 1, 3);
    gridLayout->addWidget(selectedLabel, 0, 4, 1, 6);
    gridLayout->addWidget(scrollArea, 1, 0, 1, 9);
    gridLayout->addWidget(okBtn, 2, 1, 1, 3);
    gridLayout->addWidget(cancelBtn, 2, 5, 1, 3);

#if 0
    QIcon defaultAvatar(":/resource/image/Mitsy.jpg");
    for (int i = 0; i < 10; ++i)
    {
        this->addSelectedFriend(QString::number(1000 + i), defaultAvatar, "野原美伢" + QString::number(i));
    }
#endif

    //8. 添加信号槽 处理 完成 和 取消
    connect(okBtn, &QPushButton::clicked, this, &ChooseFriendDialog::clickOkBtn);
    connect(cancelBtn, &QPushButton::clicked, this, [=](){
        this->close();
    });
}

void ChooseFriendDialog::clickOkBtn()
{
    // 1. 根据选中的好友列表中的元素 得到所有要创建群聊的成员
    QList<QString> userIdList = generateMemberList();

    // if (userIdList.size() < 3)
    // {
    //     Toast::showMessage("成员不足三个，无法创建群聊");
    //     return;
    // }

    // 2. 发送网络请求 创建群聊
    DataCenter* dataCenter = DataCenter::getInstance();
    dataCenter->createGroupChatSessionAsync(userIdList);

    // 3. 关闭窗口
    this->close();
}

QList<QString> ChooseFriendDialog::generateMemberList()
{
    QList<QString> result;

    // 1. 把自己添加到结果中
    DataCenter* dataCenter = DataCenter::getInstance();
    if (dataCenter->getMyself() == nullptr)
    {
        LOG("个人信息尚未加载");
        return result;
    }
    result.push_back(dataCenter->getMyself()->userId);
    result.push_back((dataCenter->findChatSessionById(dataCenter->getCurrentChatSessionId()))->userId);

    // 2. 遍历选中的列表
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    for (int i = 0; i < layout->count(); ++i)
    {
        auto* item = layout->itemAt(i);
        if (item == nullptr || item->widget() == nullptr)
            continue;
        auto* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        result.push_back(chooseFriendItem->getUserId());
    }
    return result;
}

void ChooseFriendDialog::initData()
{
    // 遍历好友列表 把好友列表中的所有元素 添加到窗口界面上
    DataCenter* dataCenter = DataCenter::getInstance();
    QList<UserInfo>* friendList = dataCenter->getFriendList();
    if (friendList == nullptr)
    {
        LOG("加载数据时发现好友列表为空!");
        return;
    }
    for (auto it = friendList->begin(); it != friendList->end(); ++it)
    {
        if (it->userId == this->userId)
        {
            // this->addSelectedFriend(it->userId, it->avatar, it->nickname);
            this->hideSelf(it->userId, it->avatar, it->nickname, true);
            LOG("this->hideSelf(it->userId, it->avatar, it->nickname, true);");
        }
        else
            this->addFriend(it->userId, it->avatar, it->nickname, false);
    }
}

void ChooseFriendDialog::addFriend(const QString& userId, const QIcon &avatar, const QString &name, bool checked)
{
    ChooseFriendItem* item = new ChooseFriendItem(this, userId, avatar, name, checked);

    totalContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::hideSelf(const QString &userId, const QIcon &avatar, const QString &name, bool checked)
{
    ChooseFriendItem* item = new ChooseFriendItem(this, userId, avatar, name, checked);
    item->getCheckBox()->setStyleSheet("QCheckBox { background-color: transparent; }"
                                       "QCheckBox::indicator { width: 20px; height: 20px; "
                                       "image: url(:/resource/image/dischecked.png); }");
    item->getCheckBox()->setChecked(true);
    item->getCheckBox()->setEnabled(false);
    totalContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::addSelectedFriend(const QString& userId, const QIcon &avatar, const QString &name)
{
    ChooseFriendItem* item = new ChooseFriendItem(this, userId, avatar, name, true);

    QString style = "QCheckBox { background-color: transparent; }"
                    "QCheckBox::indicator { width: 20px; height: 20px; "
                    "image: url(:/resource/image/unchecked.png); }";
    style += "QCheckBox::indicator:checked { image: url(:/resource/image/del_Item.png); }"
             "QCheckBox::indicator:hover { image: url(:/resource/image/check_clicked.png); }";

    if (++getCount() != 0)
    {
        selectedLabel->show();
        QString text = "已选择" + QString::number(getCount()) + "个联系人";
        selectedLabel->setText(text);

        QString okStyle = "QPushButton { color: rgb(255, 255, 255); background-color: rgb(7, 193, 96);"
                          "border: none; border-radius: 5px; }";
        okStyle += "QPushButton:hover { background-color: rgb(56, 205, 127); }"
                   "QPushButton:pressed { background-color: rgb(6, 173, 86); }";
        okBtn->setEnabled(true);
        okBtn->setStyleSheet(okStyle);
    }

    item->getCheckBox()->setStyleSheet(style);
    selectedContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::deleteSelectedFriend(const QString &userId)
{
    // 遍历 selectContainer 中的每个 Item, 对比每个 Item 里的 userId 是否是要删除的 userId
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    // 遍历 + 删除 从后往前
    for (int i = vlayout->count() - 1; i >= 0; --i)
    {
        auto* item = vlayout->itemAt(i);
        if (item == nullptr || item->widget() == nullptr)
            continue;
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        // 判定 userId
        if (chooseFriendItem->getUserId() != userId)
            continue;
        vlayout->removeWidget(chooseFriendItem);

        if (--getCount() != 0)
        {
            selectedLabel->show();
            QString text = "已选择" + QString::number(getCount()) + "个联系人";
            selectedLabel->setText(text);
        }
        else
        {
            selectedLabel->hide();

            QString okStyle = "QPushButton { color: rgb(158, 158, 158); background-color: rgb(235, 235, 235);"
                              "border: none; border-radius: 5px; }";
            okBtn->setStyleSheet(okStyle);
            okBtn->setEnabled(false);
        }
        // delete chooseFriendItem;
        chooseFriendItem->deleteLater();
    }

    // 遍历左侧列表，更新 checkBox 勾选状态
    QVBoxLayout* vlayoutLeft = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    for (int i = 0; i < vlayoutLeft->count(); ++i)
    {
        auto* item = vlayoutLeft->itemAt(i);
        if (item == nullptr || item->widget() == nullptr)
            continue;
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if (chooseFriendItem->getUserId() != userId)
            continue;
        chooseFriendItem->getCheckBox()->setChecked(false);
    }


}


















